package com.android.semita;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import com.android.semita.R;
import com.android.semita.controller.MessengerController;
import com.android.semita.model.Invoice;
import com.android.semita.model.Messenger;

import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity implements LoaderCallbacks<Cursor> {
	private static String APIUrl = "http://202.21.149.53/SemitaServices/api/";
	ListView lvInvoiceList;
	TextView tvTotal;
	TextView tvTotalInvoice;
	TextView tvTotalInvoiceAmount;

	ArrayList<Invoice> invoiceItems;
	InvoiceAdapter adapterInvoiceList;
	Messenger messenger;

	TextView tvMessengerID;
	TextView tvMessengerName;

	Integer messengerId;
	private String msgId;

	private static final String USERNAME = "user_name";
	//private String deliveryDate;
	private String messengerUserName;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		lvInvoiceList = (ListView) findViewById(R.id.lvInvoiceList);

		tvTotalInvoice = (TextView) findViewById(R.id.textview_count_invoice);
		tvTotalInvoiceAmount = (TextView) findViewById(R.id.textview_total);

		tvMessengerID = (TextView) findViewById(R.id.txtMessengerID);
		tvMessengerName = (TextView) findViewById(R.id.txtMessengerName);

		Intent intent = getIntent();

		messengerUserName = intent.getExtras().getString(USERNAME);
		
		//this delivery date not use but user currentdate in service
		//Demo only
		//deliveryDate =  "2013-02-11";

		// call AsyncTask for get Messenger Information
		String RequestURL = APIUrl + "Messenger?username=" + messengerUserName;
		new getJSONMessenger().execute(RequestURL);			
	}

	
	@Override
	protected void onResume() {

		super.onResume();
		// call AsyncTask for get Messenger Information
		String RequestURL = APIUrl + "Messenger?username=" + messengerUserName;
		new getJSONMessenger().execute(RequestURL);
		
		//replace double quote 
		try {				
			UpdateMessengerLocation(msgId);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}


	// call back method for AsyncTask::getJSONForInvoices()
	private void GetInvoicesFromJSON(String JSONResultString) {
		MessengerController messenger = new MessengerController();

		String jsonString = JSONResultString.substring(1,
				JSONResultString.length() - 1);
		invoiceItems = messenger.getInvoicesFromJSON(jsonString);

		adapterInvoiceList = new InvoiceAdapter(this,
				R.layout.activity_invoice_list, invoiceItems);

		lvInvoiceList.setAdapter(adapterInvoiceList);
		Summary();

	}

	// ///////////////////////////////////////////////////////////////////////////
	private class getJSONInvoices extends AsyncTask<String, Integer, String> {
		@Override
		protected void onPreExecute() {

		}

		@Override
		protected String doInBackground(String... request) {
			String returnJSONString = "";
			String requestURL = request[0];

			try {
				JSONParser jsonParser = new JSONParser();
				returnJSONString = jsonParser.getJSONFromUrl(requestURL);

				returnJSONString = returnJSONString.replace("\\", "");
			} catch (Exception e) {
				e.printStackTrace();
			}

			return returnJSONString;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
		}

		@Override
		protected void onPostExecute(String JSONResult) {
			GetInvoicesFromJSON(JSONResult);
		}
	}

	// ///////////////////////////////////////////////////////////////////////////

	// call back method for AsyncTask::getJSONMessenger()
	private void getMessengerFromJSON(String JSONResultString) {
		MessengerController messengerController = new MessengerController();
		Messenger messenger;

		String jsonString = JSONResultString.substring(1,
				JSONResultString.length() - 1);
		messenger = messengerController.getMessengerFromJSON(jsonString);

		tvMessengerID.setText(messenger.getId().toString());		
		tvMessengerName.setText(messenger.getFirstName() + " "
				+ messenger.getLastName());

		messengerId = messenger.getId();
		msgId = messengerId.toString();

		// call AsyncTask object for get list of Invoice item
		//String requestURL = APIUrl + "invoice?messengerId=" + messengerId + "&target_date=" + deliveryDate;
		
		String requestURL = APIUrl + "invoice?messengerId=" + messengerId;
		new getJSONInvoices().execute(requestURL);
		UpdateMessengerLocation(msgId);
	}

	// ///////////////////////////////////////////////////////////////////////////
	private class getJSONMessenger extends AsyncTask<String, Integer, String> {
		@Override
		protected void onPreExecute() {

		}

		@Override
		protected String doInBackground(String... request) {
			String returnJSONString = "";
			String requestURL = request[0];

			try {
				JSONParser jsonParser = new JSONParser();
				returnJSONString = jsonParser.getJSONFromUrl(requestURL);

				returnJSONString = returnJSONString.replace("\\", "");
			} catch (Exception e) {
				e.printStackTrace();
			}

			return returnJSONString;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
		}

		@Override
		protected void onPostExecute(String JSONResult) {
			getMessengerFromJSON(JSONResult);
		}
	}

	// ///////////////////////////////////////////////////////////////////////////

	public void InvoiceItemClick(View target) {
		TextView tvInvoiceNo = (TextView) target.findViewById(R.id.tvInvoiceNo);
		String invoiceNo = tvInvoiceNo.getText().toString();

		Intent intent = new Intent(this, InvoiceDetailActivity.class);
		intent.putExtra("InvoiceNo", invoiceNo);
		intent.putExtra("MessengerId", messengerId.toString());

		startActivity(intent);
	}

	private void Summary() {
		Integer countInvoice = invoiceItems.size();
		float totalInvoiceAmount = 0;
		for (int i = 0; i < invoiceItems.size(); i++) {
			totalInvoiceAmount += invoiceItems.get(i).getInvoiceAmount();
		}

		tvTotalInvoice.setText(countInvoice.toString());
		tvTotalInvoiceAmount.setText(Float.toString(totalInvoiceAmount));
	}

	@Override
	public void onBackPressed() {
		new AlertDialog.Builder(this)
				.setMessage("Are you sure you want to exit?")
				.setCancelable(false)
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								MainActivity.this.finish();
							}
						}).setNegativeButton("No", null).show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_logout:
			new AlertDialog.Builder(this)
					.setMessage("Are you sure you want to exit?")
					.setCancelable(false)
					.setPositiveButton("Yes",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									MainActivity.this.finish();
								}
							}).setNegativeButton("No", null).show();
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.invoice_detail_menu_item:
			// deletePort(info.position);
			break;
		case R.id.update_invoice_status_menu_item:
			break;
		case R.id.map_invoice_menu_item:
			// editTask(info.position);
			break;
		}

		return super.onContextItemSelected(item);

		// return true;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.context_menu, menu);

	}

	@Override
	public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
		// TODO Auto-generated method stub
		// CursorLoader loader = new CursorLoader(this,
		// PortContentProvider.CONTENT_URI, null, null, null, null);
		// return loader;
		return null;
	}

	@Override
	public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
		// TODO Auto-generated method stub

		Integer countInvoice = 0;

		while (cursor.moveToNext()) {
			countInvoice++;
		}

		// adapterInvoiceList.notifyDataSetChanged();
		tvTotalInvoice.setText(countInvoice.toString());

	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		// invoiceItems.clear();
		// adapterInvoiceList.notifyDataSetChanged();
		// CalculateTotal();

	}

/*	private boolean isInternetConnected() {
		ConnectivityManager connectMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connectMgr.getActiveNetworkInfo();

		if (networkInfo != null && networkInfo.isConnected()) {
			return true;
		} else {
			ShowAlertMessage(getString(R.string.alert_message_no_network));
			return false;
		}
	}*/

/*	private void ShowAlertMessage(String Msg) {
		AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);

		alertDialog.setMessage(Msg).setTitle(R.string.alert_title)
				.setIcon(R.drawable.ic_launcher).setCancelable(true);

		AlertDialog alert = alertDialog.create();
		alert.show();

	}*/



	private class AsyncMessengerLocation extends AsyncTask<String, Integer, String> {
		private Context context;
		private ProgressDialog dialog;

		public AsyncMessengerLocation(MainActivity mainActivity) {
			context = mainActivity;
			dialog = new ProgressDialog(context);
			dialog.setCancelable(true);
		}

		@Override
		protected void onPreExecute() {
		}

		@Override
		protected String doInBackground(String... values) {
			String returnJSONString = "";
			String MessengerId = values[0];
			String location = values[1];

			String RequestURL = APIUrl + "messengerLocation?address_gps="
					+ location + "&messenger_id=" + MessengerId;
			try {
				JSONParser jsonParser = new JSONParser();
				returnJSONString = jsonParser.getJSONFromUrl(RequestURL);

				returnJSONString = returnJSONString.replace("\\", "");
			} catch (Exception e) {
				e.printStackTrace();
			}

			return returnJSONString;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
		}

		@Override
		protected void onPostExecute(String JSONResult) {
			//dialog.dismiss();		
		}
	}

	private String getLocationString() {
		DecimalFormat decimalFormat = new DecimalFormat("#.00000");

		Location location = getCurrentLocation();
		String locationString = "";

		if (location != null) {
			locationString = decimalFormat.format(location.getLatitude()) + ","
					+ decimalFormat.format(location.getLongitude());
		}

		return locationString;
	}

	private Location getCurrentLocation() {
		LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		List<String> providers = manager.getAllProviders();
		for (String provider : providers)
			if (manager.isProviderEnabled(provider)) {
				Location loc = manager.getLastKnownLocation(provider);
				return loc;
			}

		return null;
	}

	private void UpdateMessengerLocation(String messengerId) {	
		String lat_lng = getLocationString();

		// call asyncTask for update status and rating
		new AsyncMessengerLocation(this).execute(messengerId, lat_lng);
	}
}
 